package com.ybzl.system.swagger3;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 重新改造：（BeanDefinition定义后进行扩展）
 * WebMvcRequestHandlerProvider 对象
 */
@Component
public class CompatiblePathPatternParser implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
    static final String BEAN_NAME = "webMvcRequestHandlerProvider";

    private Environment environment;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        WebMvcProperties.MatchingStrategy strategy = environment.getProperty("spring.mvc.pathmatch.matching-strategy", WebMvcProperties.MatchingStrategy.class);
        if (registry.containsBeanDefinition(BEAN_NAME) && strategy != WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER) {
            registry.removeBeanDefinition(BEAN_NAME);
            registry.registerBeanDefinition(BEAN_NAME, new RootBeanDefinition(WebMvcRequestHandlerProvider.class));
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

}
